package com.srwl.mytx.widget;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.srwl.mytx.R;
import com.srwl.mytx.widget.datechoose.OnWheelChangedListener;
import com.srwl.mytx.widget.datechoose.OnWheelScrollListener;
import com.srwl.mytx.widget.datechoose.WheelView;
import com.srwl.mytx.widget.datechoose.adapter.AbstractWheelTextAdapter;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by dahai2070 on 2016/11/13 0013.
 */
public class DateChooseDialogSingle extends android.app.AlertDialog {

    @BindView(R.id.wv_date_start)
    WheelView wv_dateStart;
    @BindView(R.id.wv_hour_start)
    WheelView wv_hourStart;
    @BindView(R.id.wv_minute_start)
    WheelView wv_minuteStart;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.top_bar_white)
    View topBar;
    private CalendarTextAdapter mDateAdapter;
    private CalendarTextAdapter mHourAdapter;
    private CalendarTextAdapter mMinuteAdapter;
    private ArrayList<String> arry_date = new ArrayList<String>();
    private ArrayList<String> arry_hour = new ArrayList<String>();
    private ArrayList<String> arry_minute = new ArrayList<String>();
    private int nowDateId = 0;
    private int nowHourId = 0;
    private int nowMinuteId = 0;
    private final int MAX_TEXT_SIZE = 18;
    private final int MIN_TEXT_SIZE = 16;
    private String str_dateStart;
    private String str_hourStart;
    private String str_minuteStart;
    private DateChooseInterface dateChooseListener;
    Context context;
    private int nowYear;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_date_choose_single_dialog);
        ButterKnife.bind(this);
        topBar.setVisibility(View.VISIBLE);
        tv_title.setText("选择时间");
        initData();
    }

    public DateChooseDialogSingle(Context context) {
        super(context, R.style.date_choose_dialog);
        this.context = context;
    }

    public void setOnDateChooseListener(DateChooseInterface dateChooseListener) {
        this.dateChooseListener = dateChooseListener;
    }

    private void initData() {
        initDateStart();
        initHourStart();
        initMinuteStart();
        initListener();
    }

    /**
     * 初始化日期
     */
    private void initDateStart() {
        Calendar nowCalendar = Calendar.getInstance();
        nowYear = nowCalendar.get(Calendar.YEAR);
        arry_date.clear();
        setDate(nowYear);
        mDateAdapter = new CalendarTextAdapter(context, arry_date, nowDateId, MAX_TEXT_SIZE, MIN_TEXT_SIZE);
        wv_dateStart.setVisibleItems(5);
        wv_dateStart.setViewAdapter(mDateAdapter);
        wv_dateStart.setCurrentItem(nowDateId);
        wv_dateStart.setCyclic(true);
        str_dateStart = arry_date.get(nowDateId);
        setTextViewStyle(str_dateStart, mDateAdapter);
    }

    /**
     * 初始化小时
     */
    private void initHourStart() {
        Calendar nowCalendar = Calendar.getInstance();
        int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);
        arry_hour.clear();
        for (int i = 0; i <= 23; i++) {
            arry_hour.add(i + "");
            if (nowHour == i) {
                nowHourId = arry_hour.size() - 1;
            }
        }

        mHourAdapter = new CalendarTextAdapter(context, arry_hour, nowHourId, MAX_TEXT_SIZE, MIN_TEXT_SIZE);
        wv_hourStart.setVisibleItems(5);
        wv_hourStart.setViewAdapter(mHourAdapter);
        wv_hourStart.setCurrentItem(nowHourId);
        str_hourStart = arry_hour.get(nowHourId) + "";
        setTextViewStyle(str_hourStart, mHourAdapter);
    }


    /**
     * 初始化分钟
     */
    private void initMinuteStart() {
        Calendar nowCalendar = Calendar.getInstance();
        int nowMinite = nowCalendar.get(Calendar.MINUTE);
        arry_minute.clear();
        for (int i = 0; i <= 59; i++) {
            arry_minute.add(i + "");
            if (nowMinite == i) {
                nowMinuteId = arry_minute.size() - 1;
            }
        }
        mMinuteAdapter = new CalendarTextAdapter(context, arry_minute, nowMinuteId, MAX_TEXT_SIZE, MIN_TEXT_SIZE);
        wv_minuteStart.setVisibleItems(5);
        wv_minuteStart.setViewAdapter(mMinuteAdapter);
        wv_minuteStart.setCurrentItem(nowMinuteId);
        str_minuteStart = arry_minute.get(nowMinuteId) + "";
        setTextViewStyle(str_minuteStart, mMinuteAdapter);
    }

    /**
     * 初始化滚动监听事件
     */
    private void initListener() {


        //日期********************
        wv_dateStart.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                String currentText = (String) mDateAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mDateAdapter);
//                mDateCalendarTextView.setTextForSendMobileCodeButton(" " + arry_date.get(wheel.getCurrentItem()));
                str_dateStart = arry_date.get(wheel.getCurrentItem());
            }
        });

        wv_dateStart.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                String currentText = (String) mDateAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mDateAdapter);
            }
        });

        //小时***********************************
        wv_hourStart.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                String currentText = (String) mHourAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mHourAdapter);
                str_hourStart = arry_hour.get(wheel.getCurrentItem()) + "";
            }

        });

        wv_hourStart.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                String currentText = (String) mHourAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mHourAdapter);
            }

        });

        //分钟********************************************
        wv_minuteStart.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                String currentText = (String) mMinuteAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mMinuteAdapter);
                str_minuteStart = arry_minute.get(wheel.getCurrentItem()) + "";
            }
        });

        wv_hourStart.addScrollingListener(new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                String currentText = (String) mMinuteAdapter.getItemText(wheel.getCurrentItem());
                setTextViewStyle(currentText, mMinuteAdapter);
            }
        });
    }


//    @NonNull
//    @Override
//    public Dialog onCreateDialog(Bundle savedInstanceState) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(context);
//        // Get the layout inflater
//        LayoutInflater inflater = context.getLayoutInflater();
//        View ll_buttonView = inflater.inflate(R.layout.fragment_date_choose_dialog, null);
//        // Inflate and set the layout for the dialog
//        // Pass null as the parent ll_buttonView because its going in the dialog layout
//        builder.setTitle("选择日期");
//
//        builder.setView(ll_buttonView)
//                // Add action buttons
//                .setPositiveButton("确定",
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onExtendMenuItemClick(DialogInterface dialog, int id) {
//                            }
//                        }).setNegativeButton("取消", null);
//        return builder.create();
//    }

    /**
     * 滚轮的adapter
     */
    private class CalendarTextAdapter extends AbstractWheelTextAdapter {
        ArrayList<String> list;

        protected CalendarTextAdapter(Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {
            super(context, R.layout.item_birth_year, R.id.tempValue, currentItem, maxsize, minsize);
            this.list = list;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            String str = list.get(index) + "";
            return str;
        }
    }

    /**
     * 将改年的所有日期写入数组
     *
     * @param year
     */
    private void setDate(int year) {
        boolean isRun = isRunNian(year);
        Calendar nowCalendar = Calendar.getInstance();
        int nowMonth = nowCalendar.get(Calendar.MONTH) + 1;
        int nowDay = nowCalendar.get(Calendar.DAY_OF_MONTH);
        for (int month = 1; month <= 12; month++) {
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    for (int day = 1; day <= 31; day++) {
                        arry_date.add(month + "月" + day + "日");

                        if (month == nowMonth && day == nowDay) {
                            nowDateId = arry_date.size() - 1;
                        }
                    }
                    break;
                case 2:
                    if (isRun) {
                        for (int day = 1; day <= 29; day++) {
                            arry_date.add(month + "月" + day + "日");
                            if (month == nowMonth && day == nowDay) {
                                nowDateId = arry_date.size() - 1;
                            }
                        }
                    } else {
                        for (int day = 1; day <= 28; day++) {
                            arry_date.add(month + "月" + day + "日");
                            if (month == nowMonth && day == nowDay) {
                                nowDateId = arry_date.size() - 1;
                            }
                        }
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    for (int day = 1; day <= 30; day++) {
                        arry_date.add(month + "月" + day + "日");
                        if (month == nowMonth && day == nowDay) {
                            nowDateId = arry_date.size() - 1;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    private boolean isRunNian(int year) {
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置文字的大小
     *
     * @param curriteItemText
     * @param adapter
     */
    public void setTextViewStyle(String curriteItemText, CalendarTextAdapter adapter) {
        ArrayList<View> arrayList = adapter.getTestViews();
        int size = arrayList.size();
        String currentText;
        for (int i = 0; i < size; i++) {
            TextView textvew = (TextView) arrayList.get(i);
            currentText = textvew.getText().toString();
            if (curriteItemText.equals(currentText)) {
                textvew.setTextSize(MAX_TEXT_SIZE);
                textvew.setTextColor(context.getResources().getColor(R.color.black));
            } else {
                textvew.setTextSize(MIN_TEXT_SIZE);
                textvew.setTextColor(context.getResources().getColor(R.color.gray_normal));
            }
        }
    }

    /**
     * 回调选中的时间（默认时间格式"yyyy-MM-dd HH:mm:ss"）
     */
    public interface DateChooseInterface {
        void getDateTime(String nowYear, String str_dateStart, String str_hourStart, String str_minuteStart);
    }

//    @OnClick(R.id.back)
//    void back() {
//        dismiss();
//    }
//
//    @OnClick(R.id.close)
//    void close() {
//        dismiss();
//    }

    @OnClick(R.id.btn_sure)
    void sure() {
        dateChooseListener.getDateTime(nowYear + "年", str_dateStart, str_hourStart, str_minuteStart);
        dismiss();
    }


}
